from flask import request, jsonify, g
from flask_jwt_extended import jwt_required
import datetime
from bson import ObjectId

from app.api.v1 import api_bp
from app import mongo
from app.utils.auth import permission_required
from app.schemas.report import ReportSchema, ReportUpdateSchema
from app.utils.common import normalize_data, paginate

@api_bp.route('/reports', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_reports():
    """获取报表列表"""
    # 获取查询参数
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 20, type=int)
    sort_by = request.args.get('sortBy', 'createdAt')
    order = request.args.get('order', 'desc')
    
    # 构建查询条件
    query = {}
    
    # 按报表类型筛选
    report_type = request.args.get('type')
    if report_type and report_type != 'all':
        query['type'] = report_type
    
    # 按状态筛选
    status = request.args.get('status')
    if status and status != 'all':
        query['status'] = status
    
    # 按日期范围筛选创建时间
    start_date = request.args.get('startDate')
    if start_date:
        try:
            start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
            if 'createdAt' not in query:
                query['createdAt'] = {}
            query['createdAt']['$gte'] = start_date
        except ValueError:
            pass
    
    end_date = request.args.get('endDate')
    if end_date:
        try:
            end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
            # 将结束日期设为当天的结束时间
            end_date = end_date.replace(hour=23, minute=59, second=59)
            if 'createdAt' not in query:
                query['createdAt'] = {}
            query['createdAt']['$lte'] = end_date
        except ValueError:
            pass
    
    # 确定排序
    sort_direction = -1 if order.lower() == 'desc' else 1
    
    # 查询数据库
    reports_cursor = mongo.db.reports.find(query).sort(sort_by, sort_direction)
    
    # 分页
    paginated_data = paginate(reports_cursor, page, limit)
    
    # 标准化数据
    reports = []
    for report in paginated_data['items']:
        # 获取创建者信息
        creator_name = ''
        if 'createdBy' in report:
            creator_id = report['createdBy']
            if isinstance(creator_id, str) and ObjectId.is_valid(creator_id):
                creator_id = ObjectId(creator_id)
            creator = mongo.db.users.find_one({'_id': creator_id})
            if creator:
                creator_name = creator.get('name', '')
        
        # 标准化报表数据
        normalized_report = normalize_data(report)
        normalized_report['creatorName'] = creator_name
        reports.append(normalized_report)
    
    return jsonify({
        'success': True,
        'data': {
            'total': paginated_data['total'],
            'page': paginated_data['page'],
            'limit': paginated_data['per_page'],
            'reports': reports
        }
    }), 200

@api_bp.route('/reports/<id>', methods=['GET'])
@jwt_required()
@permission_required('report:read')
def get_report(id):
    """获取报表详情"""
    # 查询报表
    report = None
    if ObjectId.is_valid(id):
        report = mongo.db.reports.find_one({'_id': ObjectId(id)})
    
    if not report:
        return jsonify({
            'success': False,
            'message': '报表不存在'
        }), 404
    
    # 获取创建者信息
    creator_info = None
    if 'createdBy' in report:
        creator_id = report['createdBy']
        if isinstance(creator_id, str) and ObjectId.is_valid(creator_id):
            creator_id = ObjectId(creator_id)
        creator = mongo.db.users.find_one({'_id': creator_id})
        if creator:
            creator_info = {
                'id': str(creator['_id']),
                'name': creator.get('name', ''),
                'role': creator.get('role', '')
            }
    
    # 标准化数据
    normalized_report = normalize_data(report)
    normalized_report['creatorInfo'] = creator_info
    
    return jsonify({
        'success': True,
        'data': normalized_report
    }), 200

@api_bp.route('/reports', methods=['POST'])
@jwt_required()
@permission_required('report:create')
def create_report():
    """创建报表"""
    # 验证请求数据
    schema = ReportSchema()
    errors = schema.validate(request.json)
    if errors:
        return jsonify({
            'success': False,
            'message': '请求数据验证失败',
            'errors': errors
        }), 400
    
    data = request.json
    
    # 设置创建者
    data['createdBy'] = str(g.current_user['_id'])
    
    # 设置创建时间和更新时间
    now = datetime.datetime.utcnow()
    data['createdAt'] = now
    data['updatedAt'] = now
    
    # 保存到数据库
    result = mongo.db.reports.insert_one(data)
    
    return jsonify({
        'success': True,
        'message': '报表创建成功',
        'data': {
            'id': str(result.inserted_id),
            'name': data['name'],
            'type': data['type'],
            'createdAt': now.isoformat()
        }
    }), 201

@api_bp.route('/reports/<id>', methods=['PUT'])
@jwt_required()
@permission_required('report:update')
def update_report(id):
    """更新报表"""
    # 查询报表
    report = None
    if ObjectId.is_valid(id):
        report = mongo.db.reports.find_one({'_id': ObjectId(id)})
    
    if not report:
        return jsonify({
            'success': False,
            'message': '报表不存在'
        }), 404
    
    # 验证请求数据
    schema = ReportUpdateSchema()
    errors = schema.validate(request.json)
    if errors:
        return jsonify({
            'success': False,
            'message': '请求数据验证失败',
            'errors': errors
        }), 400
    
    data = request.json
    
    # 更新时间
    data['updatedAt'] = datetime.datetime.utcnow()
    
    # 更新数据库
    mongo.db.reports.update_one({'_id': ObjectId(id)}, {'$set': data})
    
    return jsonify({
        'success': True,
        'message': '报表更新成功',
        'data': None
    }), 200

@api_bp.route('/reports/<id>', methods=['DELETE'])
@jwt_required()
@permission_required('report:delete')
def delete_report(id):
    """删除报表"""
    # 查询报表
    report = None
    if ObjectId.is_valid(id):
        report = mongo.db.reports.find_one({'_id': ObjectId(id)})
    
    if not report:
        return jsonify({
            'success': False,
            'message': '报表不存在'
        }), 404
    
    # 删除数据库中的报表
    mongo.db.reports.delete_one({'_id': ObjectId(id)})
    
    return jsonify({
        'success': True,
        'message': '报表删除成功',
        'data': None
    }), 200

@api_bp.route('/reports/<id>/generate', methods=['POST'])
@jwt_required()
@permission_required('report:generate')
def generate_report(id):
    """手动生成报表"""
    # 查询报表
    report = None
    if ObjectId.is_valid(id):
        report = mongo.db.reports.find_one({'_id': ObjectId(id)})
    
    if not report:
        return jsonify({
            'success': False,
            'message': '报表不存在'
        }), 404
    
    # 这里应该实现报表生成的逻辑
    # 为简化示例，这里只更新lastRun信息
    now = datetime.datetime.utcnow()
    last_run = {
        'time': now,
        'status': '成功',
        'message': '报表生成成功',
        'resultUrl': f"/reports/files/{id}_{now.strftime('%Y%m%d%H%M%S')}.pdf"
    }
    
    # 更新报表的lastRun信息
    mongo.db.reports.update_one(
        {'_id': ObjectId(id)},
        {
            '$set': {
                'lastRun': last_run,
                'updatedAt': now
            }
        }
    )
    
    return jsonify({
        'success': True,
        'message': '报表生成成功',
        'data': {
            'lastRun': {
                'time': now.isoformat(),
                'status': '成功',
                'resultUrl': last_run['resultUrl']
            }
        }
    }), 200 